package com.example.dao.impl;

import com.example.dao.BookDao;
import com.example.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class BookDaoImpl implements BookDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Book book) {
        String sql = "insert into book (name,author,publisher,price,inventory) values (?,?,?,?);";
        return this.jdbcTemplate.update(sql,book.getName(),
                book.getAuthor(),book.getPublisher(),
                book.getPrice(),book.getInventory());
    }

    @Override
    public Book queryById(int id) {
        String sql = "SELECT * FROM book WHERE id= ?";
        RowMapper<Book> mapper = ((rs, rowNum) -> {
            Book book = new Book();
            book.setId(rs.getInt("id"));
            book.setPublisher(rs.getString("publisher"));
            book.setName(rs.getString("name"));
            book.setAuthor(rs.getString("author"));
            book.setPrice(rs.getInt("price"));
            book.setInventory(rs.getInt("inventory"));
            return book;

        });
        return this.jdbcTemplate.queryForObject(sql,mapper,id);
    }


    @Override
    public int update(Book book) {
        String sql = "update book set name = ?,author = ?,publisher = ?,price = ? ,inventory =? where id = ?";
        return this.jdbcTemplate.update(sql,book.getName(),
                book.getAuthor(),book.getPublisher(),
                book.getPrice(), book.getId(),
                book.getInventory());
    }

    @Override
    public int delete(int id) {
        String sql = "DELETE FROM book WHERE id = ?";
        return this.jdbcTemplate.update(sql,id);
    }


}
